from PyQt5.QtCore import QObject, pyqtSignal
from trace_visualizer_py.common import *

class BasicConfig(QObject):
    config_changed = pyqtSignal(str, object)  # 配置变化信号

    def __init__(self):
        super().__init__()
        
        self._config = {
            "poolWidth": 50,
            "poolLength": 100,
            "poolAngle": 0,
            "UWB1_pos": [0, 0],
            "UWB2_pos": [10, 0],
            "UWB3_pos": [0, 10],
            "PID1": [0, 0, 0],
            "PID2": [0, 0, 0],
            "shipState": ShipState.STOP,
            "shipX": 0,
            "shipY": 0
        }

    def get(self, key):
        return self._config.get(key)

    def set(self, key, value):
        if self._config.get(key) != value:
            self._config[key] = value
            self.config_changed.emit(key, value)  # 发射信号
            print(f"{key} now is {value}", end='')

    def save_to_file(self, filename="config.json"):
        import json
        try:
            with open(filename, "w") as f:
                json.dump(self._config, f)
            print('保存配置成功……', end='')
        except:
            print('保存配置失败……', end='')

    def load_from_file(self, filename="config.json"):
        import json
        try:
            with open(filename, "r") as f:
                cfg = json.load(f)
                for k,v in cfg.items():
                    if self.get(k) != v:
                        self.set(k, v)
        except FileNotFoundError:
            print("配置文件不存在，使用默认值", end='')

        except FileNotFoundError:
            print("配置文件不存在，使用默认值", end='')

common_data['cfg_basic'] = BasicConfig()